<?php

require_once ROOT_PATH . '/lib/confs/Conf.php';
require_once ROOT_PATH . '/lib/dao/DMLFunctions.php';
require_once ROOT_PATH . '/lib/dao/SQLQBuilder.php';
require_once ROOT_PATH . '/lib/common/CommonFunctions.php';
require_once ROOT_PATH . '/lib/common/UniqueIDGenerator.php';
require_once ROOT_PATH . '/lib/common/SearchObject.php';
require_once ROOT_PATH . '/lib/models/hrfunct/EmpInfo.php';

require_once ROOT_PATH . '/lib/models/surveys/Answers.php';//Chinh Nguyen add

require_once ROOT_PATH . '/lib/models/surveys/Options.php';//Chinh Nguyen add

require_once ROOT_PATH . '/lib/models/surveys/Questions.php';//Chinh Nguyen add

require_once ROOT_PATH . '/lib/models/surveys/Surveys.php';//Chinh Nguyen add

class Answers {

	const TABLE_NAME = 'hs_hr_sur_answers';
	
	const DB_FIELD_ANSWERS_ID = 'answer_id';
	const DB_FIELD_ANSWERS_VALUE = 'answer_value';
	const DB_FIELD_ANSWERS_USER = 'answer_user';
	const DB_FIELD_QUESTIONS_ID = 'question_id';
	const DB_FIELD_SURVEY_ID = 'survey_id';
	const DB_FIELD_DATE_SUBMIT = 'date_submit';
	
	private $answer_id;
	private $answer_value;
	private $answer_user;
	private $question_id;
	private $survey_id;
	private $date_submit;
	
	public function __construct($answer_id = null) {
		$this->answer_id = $answer_id;
	}

	public function setId($id) {
		$this->answer_id = $id;
	}

	public function setValue($value) {
		$this->answer_value = $value;
	}
	
	public function setUser($user) {
		$this->answer_user = $user;
	}
	
	public function setQuestionId($id) {
		$this->question_id = $id;
	}
	
	public function setSurveyId($id) {
		$this->survey_id = $id;
	}
	
	public function setDateSubmit($date) {
		$this->date_submit = $date;
	}

	public function getId() {
		return $this->answer_id;
	}
	
	public function getValue() {
		return $this->answer_value;
	}
	
	public function getUser() {
		return $this->answer_user;
	}
	
	public function getQuestionID() {
		return $this->question_id;
	}
	
	public function getSurveyId() {
		return $this->survey_id;
	}
	
	public function getDateSubmit() {
		return $this->date_submit;
	}

    public function save() {
		if (isset($this->answer_id)) {
			return $this->_update();
		} else {
			return $this->_insert();
		}
    }

	public static function delete($ids) {

		$count = 0;
		if (!is_array($ids)) {
			throw new AnswersException("Invalid parameter to delete(): ids should be an array", AnswersException::INVALID_PARAMETER);
		}

		foreach ($ids as $id) {
			if (!CommonFunctions::isValidId($id)) {
				throw new AnswersException("Invalid parameter to delete(): id = $id", AnswersException::INVALID_PARAMETER);
			}
		}

		if (!empty($ids)) {

			$sql = sprintf("DELETE FROM %s WHERE %s IN (%s)", self::TABLE_NAME,
			                self::DB_FIELD_NEWS_ID, implode(",", $ids));

			$conn = new DMLFunctions();
			$result = $conn->executeQuery($sql);
			if ($result) {
				$count = mysql_affected_rows();
			}
		}
		return $count;
	}


	public static function getAll() {
		return self::_getList();
	}
	
	public static function getAnswersByQuestionSurvey($suvey_id,$question_id) {
		$condition[0]= "(".self::DB_FIELD_SURVEY_ID." = ".$suvey_id .")";
		$condition[1]= "(".self::DB_FIELD_QUESTIONS_ID." = ".$question_id .")";
		return self::_getList($condition);		
	}
	
	public static function getTotalAnswersBySurvey($suvey_id) {
		$sql = sprintf("Select answer_user FROM %s WHERE %s = (%s) GROUP BY answer_user", self::TABLE_NAME,
			                self::DB_FIELD_SURVEY_ID,$suvey_id);
		//die($sql);
		$conn = new DMLFunctions();
		$result = $conn->executeQuery($sql);
		if ($result) {
				$count = mysql_affected_rows();
		}		
		return $count;
	}
	
	public static function getTotalAnswersByUser($suvey_id,$user) {
		$sql = sprintf("Select answer_user FROM %s WHERE %s = %s AND %s = %s ", self::TABLE_NAME,
			                self::DB_FIELD_SURVEY_ID,$suvey_id,self::DB_FIELD_ANSWERS_USER,$user);
		
		$conn = new DMLFunctions();
		$result = $conn->executeQuery($sql);
		if ($result) {
				$count = mysql_affected_rows();
		}		
		return $count;
	}
	
	public static function getAnswersBySurvey($suvey_id) {
		$sql = sprintf("Select * FROM %s WHERE %s = (%s) GROUP BY answer_user", self::TABLE_NAME,
			                self::DB_FIELD_SURVEY_ID,$suvey_id);
		
		$conn = new DMLFunctions();
		$result = $conn->executeQuery($sql);
		while ($result && ($row = mysql_fetch_assoc($result))) {
			$actList[] = self::_createFromRow($row);
		}
		return $actList;
	}
	
	public static function getAnswersBySurveyId($suvey_id) {
		$sql = sprintf("Select * FROM %s WHERE %s = (%s)", self::TABLE_NAME,
			                self::DB_FIELD_SURVEY_ID,$suvey_id);
		
		$conn = new DMLFunctions();
		$result = $conn->executeQuery($sql);
		$actList = array();
		while ($result && ($row = mysql_fetch_assoc($result))) {
			$actList[] = self::_createFromRow($row);
		}
		return $actList;
	}
	
	
	public static function getCustomAnswersBySurveyUser($suvey_id,$question_id,$user) {
		$condition[0]= "(".self::DB_FIELD_SURVEY_ID." = ".$suvey_id .")";
		$condition[1]= "(".self::DB_FIELD_ANSWERS_USER." = ".$user.")";		
		if($question_id != null){		
			$condition[2]= "(".self::DB_FIELD_QUESTIONS_ID." = ".$question_id .")";
		}
		return self::_getList($condition);	
	}
	
	
	
	public static function getAnswersByOptionQuestionSurvey($suvey_id,$question_id,$option_id,$user) {
		
		$condition[0]= "(".self::DB_FIELD_SURVEY_ID." = ".$suvey_id .")";
		$condition[1]= "(".self::DB_FIELD_QUESTIONS_ID." = ".$question_id .")";
		$condition[2]= "(".self::DB_FIELD_ANSWERS_VALUE." = ".$option_id .")";
		$condition[3]= "(".self::DB_FIELD_ANSWERS_USER." = ".$user.")";		
		return self::_getList($condition);		
	}
	
	public static function getAnswersBySurveyUser($suvey_id,$user) {
		
		$condition[0]= "(".self::DB_FIELD_SURVEY_ID." = ".$suvey_id .")";
		$condition[1]= "(".self::DB_FIELD_ANSWERS_USER." = ".$user.")";
		
		return self::_getList($condition);		
	}
	
	public static function getAnswersScoreBySurveyUser($suvey_id,$user) {
		
		//$condition[0]= "(".self::DB_FIELD_SURVEY_ID." = ".$suvey_id .")";
		//$condition[1]= "(".self::DB_FIELD_ANSWERS_USER." = ".$user.")";
		//$answers =  self::_getList($condition);
		$questions = Questions::getQuestionsBySurvey($suvey_id);
		if(count($questions)>0){
			$totalscore = 0;
			$personalScore =0;	
			foreach ($questions as $question){
				if($question->getAnswerType() != 4)
					$totalscore ++;	
				$options = Options::getOptionsByQuestions($question->getId());
				if(count($options)>0){
					$totalRightAnswer = 0;
					$rightAnswer = 0;
					$wrongAnswer = 0;
					foreach ($options as $option){
						if($option->getValue()==1)
					    	$totalRightAnswer++;		
						$checkedOptions = Answers::getAnswersByOptionQuestionSurvey($suvey_id,$question->getId(),$option->getId(),$user);
						if(count($checkedOptions)>0){
							$checkedOptionsId = array();
							$k=0;
							foreach($checkedOptions as $item){
			    				$checkedOptionsId[$k]= $item->getValue();
			    				$k++;
			    			}
			    			if(in_array($option->getId(),$checkedOptionsId)&& $option->getValue()==1 ) {
			    				$rightAnswer ++;
			    			}else if(in_array($option->getId(),$checkedOptionsId)&& $option->getValue()!=1 ) { 
			    				$wrongAnswer++;
			    			}	
						}					    
					}
					if($totalRightAnswer==0)
						$personalScore += 0;
					else{
						if(round($rightAnswer/$totalRightAnswer,1)== 1 && $wrongAnswer ==0)
							$personalScore += 1;
						}
				}
			}
		}
		$array['personalscore']=$personalScore;
		$array['totalscore']=$totalscore;
		return $array;
			
	}
	
	

	private static function _getList($selectCondition = null) {
		$fields[0] = self::DB_FIELD_ANSWERS_ID;		
		$fields[1] = self::DB_FIELD_ANSWERS_VALUE;
		$fields[2] = self::DB_FIELD_ANSWERS_USER;
		$fields[3] = self::DB_FIELD_QUESTIONS_ID;
		$fields[4] = self::DB_FIELD_SURVEY_ID;
		$fields[5] = self::DB_FIELD_DATE_SUBMIT;
		
		$tables[0] = self::TABLE_NAME ;
		
		$sqlBuilder = new SQLQBuilder();
		$sql = $sqlBuilder->simpleSelect($tables[0],$fields,$selectCondition);
		//die($sql);
		$actList = array();

		$conn = new DMLFunctions();
		$result = $conn->executeQuery($sql);
	
		while ($result && ($row = mysql_fetch_assoc($result))) {
				
			$actList[] = self::_createFromRow($row);
			
		}
		return $actList;
	}

	private function _insert() {
				
		//$fields[0] = self::DB_FIELD_ANSWERS_ID;		
		$fields[0] = self::DB_FIELD_ANSWERS_VALUE;
		$fields[1] = self::DB_FIELD_ANSWERS_USER;
		$fields[2] = self::DB_FIELD_QUESTIONS_ID;
		$fields[3] = self::DB_FIELD_SURVEY_ID;		
		$fields[4] = self::DB_FIELD_DATE_SUBMIT;

		//$values[0] = $this->answer_id;
		$values[0] = "'{$this->answer_value}'";
		$values[1] = "'{$this->answer_user}'";
		$values[2] = $this->question_id;
		$values[3] = $this->survey_id;
		$today = date("Y-m-d"); 
		$values[4] = $today;
		
		$sqlBuilder = new SQLQBuilder();
		$sqlBuilder->table_name = self::TABLE_NAME;
		$sqlBuilder->flg_insert = 'true';
		$sqlBuilder->arr_insert = $values;
		$sqlBuilder->arr_insertfield = $fields;

		$sql = $sqlBuilder->addNewRecordFeature2();
	
		$conn = new DMLFunctions();

		$result = $conn->executeQuery($sql);
		if (!$result || (mysql_affected_rows() != 1)) {
			throw new OptionsException("Insert failed. ", OptionsException::DB_ERROR);
		}

		return $this->answer_id;
	}

	private function _update() {

		$fields[0] = self::DB_FIELD_ANSWERS_ID;		
		$fields[1] = self::DB_FIELD_ANSWERS_VALUE;
		$fields[2] = self::DB_FIELD_ANSWERS_USER;
		$fields[3] = self::DB_FIELD_QUESTIONS_ID;
		$fields[4] = self::DB_FIELD_SURVEY_ID;
		$fields[5] = self::DB_FIELD_DATE_SUBMIT;		

		$values[0] = $this->answer_id;
		$values[1] = "'{$this->answer_value}'";
		$values[2] = "'{$this->answer_user}'";
		$values[3] = $this->question_id;
		$values[4] = $this->survey_id;
		$today =  date("Y-m-d"); 
		$values[5] = $today;
		
		$sqlBuilder = new SQLQBuilder();
		$sqlBuilder->table_name = self::TABLE_NAME;
		$sqlBuilder->flg_update = 'true';
		$sqlBuilder->arr_update = $fields;
		$sqlBuilder->arr_updateRecList = $values;

		$sql = $sqlBuilder->addUpdateRecord1(0);

		$conn = new DMLFunctions();
		$result = $conn->executeQuery($sql);

		if (!$result) {
			throw new OptionsException("Update failed. SQL=$sql", OptionsException::DB_ERROR);
		}
		return $this->answer_id;
	}

    private static function _createFromRow($row) {
    	
    	
    	$answer = new Answers($row[self::DB_FIELD_ANSWERS_ID]);
    	
    	$answer->setValue($row[self::DB_FIELD_ANSWERS_VALUE]);
    	$answer->setUser($row[self::DB_FIELD_ANSWERS_USER]);    	
    	$answer->setQuestionId($row[self::DB_FIELD_QUESTIONS_ID]);
    	$answer->setSurveyId($row[self::DB_FIELD_QUESTIONS_ID]);
    	$answer->setDateSubmit($row[self::DB_FIELD_DATE_SUBMIT]);
    	
    	return $answer;
    }

}

class AnswersException extends Exception {
	const INVALID_PARAMETER = 0;
	const DB_ERROR = 1;
}
?>
